<template>
    <div id="MapList" v-show="showFlag">
      <header class="header">
        <div class="title">
          <img src="../assets/images/01_11.png" alt="" class="img_zuo" @click="hideMap" />
          <div>地图</div>
          <div class="btn-queding" @click="submit">
            确定
          </div>
          <!--<span class="btn-add" @click="addNew">+</span>
          <img src="../assets/images/big.png" alt="" class="btn-search" @click="search" />-->
        </div>
      </header>
      <div class="main">

        <div class="ditu  yc">
        	<div id="ditu"></div>
        	<!-- 地点列表 -->
        	<div class="lie_list">
            <!--
            <div class="lie_list_item lie_list_item_bg">测试</div>
            <div class="lie_list_item">测试</div>
            -->
            <div class="lie_list_item" v-for="(obj,i) of list" @click="selectDidian(obj)" :class="{'lie_list_item_bg':(checked.address==obj.address)&&(checked.name==obj.name)}">{{obj.name}}</div>
          </div>
        </div>

      </div>
    </div>
</template>
<script>
/**
 * 使用方法
 * 引入本组件
 *    import MapPos from "../MapPos.vue";
 * 在vue里添加组件
 * components: {
      MapPos
    }
 * 放在在页面上
 *    <MapPos ref="mapList" @closeMap="getMapResult"></MapPos>
 * 需要设定ref，调用这个组件的方法的时候需要用到
 *
 * 通过设定的ref显示地图并且初始化，参数有两个，都可以为空，第一个为地址，第二个为逗号拼接的经纬度字符串
 *    this.$refs.mapList.init('地址','20,33');
 * 绑定一个函数(比如getMapResult)到closeMap事件用来接收定位返回的信息，参数为一个数组
 *    getMapResult(mapResult){
        //mapResult为地图定位的返回信息
        //mapResult.address 地址
        //mapResult.jd 经度
        //mapResult.wd 纬度
        //mapResult.name 地名
      },
 *
 */
import { Dialog } from "vant";
import terminal from "../assets/js/terminal";
export default {
    data(){
        return{
          map:null,
          list:[],
          showFlag:false,
          jwd:'',
          checked:{//选中的
            address:null,
            jd:null,
            wd:null,
            name:null
          },
          markerObj:null
        }
    },
    methods:{
      submit(){
        if(this.checked.jd&&this.checked.wd){
          localStorage.setItem("MapPosResult",JSON.stringify(this.checked));
          this.hideMap();
        }
      },
      //初始化
      init(address,jwd){
        console.log('address:'+address);
        console.log('jwd:'+jwd);
        var _this = this;
        //_this.showFlag = true;
        try{
          //验证是否设置了定位权限
          plus.geolocation.getCurrentPosition(function(p) {
            //p.coords.latitude
            //p.coords.longitude
            //p.coords.altitude
            _this.showFlag = true;
            setTimeout(function(){
              _this.getMap(address,jwd);
            },1000);
          }, function(e) {
          	console.log('Gelocation Error: code - ' + e.code + '; message - ' + e.message);
          	var isAndroid = terminal.terminals().android;
            Dialog.confirm({
              title: '提示',
              message: '请打开定位权限!',
              confirmButtonText: "去设置", //改变确认按钮上显示的文字
              cancelButtonText: "取消" //改变取消按钮上显示的文字
            }).then(() => {
              //console.log("点击了确认按钮噢")
              if(isAndroid){//安卓系统
                var main = plus.android.runtimeMainActivity();
                var Intent = plus.android.importClass("android.content.Intent");
                var mIntent = new Intent('android.settings.LOCATION_SOURCE_SETTINGS');
                main.startActivity(mIntent);
              }else{//IOS系统
                var UIApplication = plus.ios.import("UIApplication");
                var NSURL = plus.ios.import("NSURL");
                var setting = NSURL.URLWithString("app-settings:");
                var application = UIApplication.sharedApplication();
                application.openURL(setting);
                plus.ios.deleteObject(setting);
                plus.ios.deleteObject(application);
              }
            }).catch(() => {
              //console.log("点击了取消按钮噢")
            });
            _this.showFlag = true;
          });
        }catch(e){
          console.log(e.message);
          _this.showFlag = true;
        }
      },
      //获取地图
      getMap(address,jwd){
        var _this = this;
        var sort = null;
        var no_jwd = false; //有地点没经纬度
        if(!address){
          console.log("没得地点没经纬度")
        }else{
          if(!jwd){
            console.log("有地点没经纬度")
            //no_jwd = true;
          }else{
            console.log("有地点有经纬度")
            sort = 1;
          }
        }
        _this.checked = {
          address:null,
          jd:null,
          wd:null,
          name:null
        };
        var _map = plus.maps.getMapById('ditu');
        if(_map){
          _map.close();
        }
        _this.map = new plus.maps.Map("ditu");
        _this.map.showZoomControls(true); //显示缩放控件
        if(no_jwd){
          let pcenter = new plus.maps.Point(_this.$global_msg.centerJwd.jd, _this.$global_msg.centerJwd.wd);
          _this.map.setZoom(13);
          _this.map.setCenter(pcenter)
        }else{
          _this.map.getUserLocation(function(state, point) {
          	if (0 == state) {
          		var pcenter = new plus.maps.Point(point.longitude, point.latitude); // 地图中心点
          		if (sort == 1) {
              	var jd = jwd.split(',')[0];
              	var wd = jwd.split(',')[1];
              	pcenter = new plus.maps.Point(jd, wd); // 地图中心点
              }
              // 设置地图的中心点和缩放级别
          		_this.map.setCenter(pcenter);
          		//显示用户当前位置
          		_this.Display_the_current_location(pcenter);
          		//检索附近地名
          		_this.Access_to_nearby_locations(pcenter, sort);
          	} else {
          		alert("定位失败!");
          	}
          })
        }
        document.documentElement.style.height = '100%'
        document.documentElement.style.overflow = 'hidden'
        document.body.style.height = '100%'
        document.body.style.overflow = 'hidden'

        //用户点击地图
        _this.map.onclick = function (point) {
        	var marker = new plus.maps.Marker(point);
        	marker.setIcon("/static/dt_03.gif");
        	marker.setDraggable(true);
        	_this.map.removeOverlay(_this.markerObj);
        	_this.map.addOverlay(marker);
        	_this.markerObj = marker;
        	//查找附近地点
        	var searchObj = new plus.maps.Search(_this.map);
        	searchObj.poiSearchNearBy('', point, 100);
        	searchObj.onPoiSearchComplete = function (state, result) {
        		if (result['poiList'].length) {
        			var poi = result['poiList'][0];
        			marker.setLabel(poi['name']);
        			//列出所有附近
              _this.list = [];
        			$.each(result['poiList'], function (i, item) {
                  var obj = {
                    address:item.address,//地址
                    jd:item.point.longitude,//经度
                    wd:item.point.latitude,//纬度
                    name:item.name
                  };
                  _this.list.push(obj);
                  if(i==0){
                    _this.checked = obj;
                    _this.BiaoDian(obj);
                  }
        			});
        		}
        	}
        }
      },
      //显示用户当前位置
      Display_the_current_location(pcenter){
        var _this = this;
        _this.map.setZoom(18);
        // map.showUserLocation(true); // 设置是否显示用户的位置
        _this.map.showZoomControls(true); //显示缩放控件
        _this.map.setCenter(pcenter); // 设置地图的中心点和缩放级别
      },
      //检索附近地名
      Access_to_nearby_locations(pcenter, sort){
        var _this = this;
        var searchObj = new plus.maps.Search(_this.map);
        //检索完成事件
        searchObj.onPoiSearchComplete = function(state, result) {
        	// console.log("onPoiSearchComplete: " + state + " , " + result.currentNumber);
        	if (state == 0) {
        		if (result.currentNumber <= 0) {
        			//没有检索到结果
        			// alert("没有检索到结果");
        		}
        		var num = sort == 1 ? 1 : result.currentNumber;
            _this.list = [];
        		for (var i = 0; i < num; i++) {
        			var pos = result.getPosition(i);
        			// alert(JSON.stringify(pos))
        			// var marker = new plus.maps.Marker(pos.point);
        			// marker.setLabel(pos.name);
        			// map.addOverlay(marker);
              var obj = {
                address:pos.address,//地址
                jd:pos.point.longitude,//经度
                wd:pos.point.latitude,//纬度
                name:pos.name
              };
              _this.list.push(obj);

              if(i==0){
                _this.BiaoDian(obj);
              }
        		}

        	} else {
        		alert("检索附近地名失败");
        	}
        }

        // 在当前位置周围1千米内对关键字“”进行检索
        searchObj.poiSearchNearBy("", pcenter, 1000);
      },
      selectDidian(obj){//列表选中
        var _this = this;
        //var jd = obj.jd;
        //var wd = obj.wd;
        //var point = new plus.maps.Point(jd, wd); // 地图中心点
        //_this.map.onclick(point);
        _this.BiaoDian(obj);
      },
      BiaoDian(obj, sort){//在地图上标点
        var _this = this;
        console.log('BiaoDian',obj)
        _this.checked = obj;
        var jd = obj.jd;
        var wd = obj.wd;
        var name = obj.name;
        var address = obj.address;
        var pcenter = new plus.maps.Point(jd, wd); // 地图中心点
        _this.map.setCenter(pcenter); // 设置地图的中心点和缩放级别


        var marker = new plus.maps.Marker(pcenter);
        marker.setIcon("/static/dt_03.gif");
        marker.setDraggable(true);
        marker.setLabel(name);
        var bubble = new plus.maps.Bubble(address);
        marker.setBubble(bubble);
        // map.clearOverlays();
        // setTimeout(function() {
        // }, 1000);
        _this.map.removeOverlay(_this.markerObj);
        _this.map.addOverlay(marker);
        _this.markerObj = marker;
        marker.onDrag = function(target) {
        	$(".lie_list").html("");
        	// alert(JSON.stringify(target.getPoint()))
        	var pcenter = new plus.maps.Point(target.getPoint().longitude, target.getPoint().latitude); // 地图中心点
        	_this.map.setCenter(pcenter); // 设置地图的中心点和缩放级别
        	_this.Access_to_nearby_locations(pcenter,sort);
        }
      },
      hideMap(){//关闭地图
        this.$router.back()
      },
      addNew(){//搜索
        //console.log(this.checked)
      },
      search(){//新增
        //console.log(this.checked)
      },
      plusReady: function () {
        var _this = this;
        //验证是否设置了定位权限
        plus.geolocation.getCurrentPosition(function(p) {
          //p.coords.latitude
          //p.coords.longitude
          //p.coords.altitude
        }, function(e) {
        	console.log('Gelocation Error: code - ' + e.code + '; message - ' + e.message);
        	//alert("请打开定位权限!");
        	_this.showFlag = false;
        });
      },
    },
    beforeCreate() {
      document.addEventListener("plusready", this.plusReady, false);
    },
    beforeRouteLeave(to, form, next) {
      if(this.map){
        this.map.close();
      }
      try{
        var _map = plus.maps.getMapById('ditu');
        if(_map){
          _map.close();
        }
      }catch(e){
        //TODO handle the exception
      }
      this.map = null;
      this.showFlag = false;
      document.documentElement.style.height = '100%'
      document.documentElement.style.overflow = 'auto'
      document.body.style.height = '100%'
      document.body.style.overflow = 'auto'
      next()
    },
    mounted() {
      //this.getMap();
      var MapPosObj = localStorage.getItem("MapPosObj")?JSON.parse(localStorage.getItem("MapPosObj")):{};
      this.init(MapPosObj.address,MapPosObj.jwd);
    },
    created(){
      //this.$maps.hqqx()
    }
}
</script>
<style scoped>
  #MapList{
    width: 100%;
    height: 100%;
    z-index: 40;
    position: fixed;
    top: 0;
    left: 0;
    display: flex;
    flex-direction: column;
  }
  .header {
    height: 1.8519rem;
    background: #007aff;
    padding-top: 0.8333rem;
    box-sizing: border-box;
    width: 100%;
    font-size: 0.388888rem;
    position: relative;
  }

  .title {
    padding: 0 0.3704rem;
    display: flex;
    align-items: center;
    color: #fff;
    position: relative;
  }

  .title>div {
    width: 100%;
    font-size: 0.4444rem;
    text-align: center;
  }

  .img_zuo {
    width: 0.2593rem;
    height: 0.463rem;
  }
  .btn-search{
    position: absolute;
    right: 1.388888rem;
    bottom: 0.388888rem;
    width: 0.629629rem;
    height: 0.629629rem;
  }
  .btn-add{
    position: absolute;
    right: 0.37037rem;
    font-size: 1.111111rem !important;
  }

  .btn-queding {
    position: absolute;
    right: 0.37037rem;
    width: auto !important;
    height: 100%;
    bottom: 0;
    display: flex;
    align-items: center;
  }
  .btn-queding img {
    width: 0.529629rem;
    height: 0.529629rem;
  }

  .main {
    /*padding-top: 1.8519rem;*/
    /* height: 100vh; */
    box-sizing: border-box;
    background: #fff;
    /*padding-bottom: 3.796314814814815rem; */
    /* padding-top: 10.0008px; */
    flex: 1;
  }

  .ditu {
  	width: 100%;
  	height: 100%;
  	background: #FFFFFF;
  	display: flex;
  	overflow: hidden;
  	box-sizing: border-box;
  	flex-wrap: wrap;
    flex-direction: column;
  }
  #ditu {
  	width: 100%;
  	flex: 1;
  	background: #FFFFFF;
  }

  .lie_list {
  	width: 100%;
  	height: 8.3333rem;
  	background: #fff;
  	overflow: scroll;
  }

  .lie_list_item {
  	height: 1.2963rem;
  	line-height: 1.2963rem;
  	border-bottom: 0.018518518518518517rem solid #f1f1f1;
  	padding-left: 0.2778rem;
  }

  .head_right {
  	color: #fff;
  	position: absolute;
  	right: 0.3889rem;
  	top: 0.779rem;
  	height: 44px;
  	font-size: 0.4259rem;
  	line-height: 44px;
  }

  .lie_list_item_bg {
  	background: #2E5DFE;
  	color: #fff;
  }
</style>
